<?
error_reporting(E_ERROR);
ini_set("display_errors", true);
include_once 'appinclude.php';

$entry = $_REQUEST['suggest_typed'];
function SearchCities($q)
{
	$conn = getConnection();
	if(is_numeric($q))
		$sql = "SELECT City, State, Zip FROM US_Zip_Codes WHERE zip LIKE '%$q%' GROUP BY City, State LIMIT 5";
	else
	{
		$sql = "SELECT City, State FROM US_Zip_Codes WHERE 1=1 ";
		$list = explode(',',$q);
		foreach($list as $item)
		{
			$item = trim($item);
			$sql .= " AND (City LIKE '%$item%' or State LIKE '%$item%') ";
		}
		$sql .= " GROUP BY City, State LIMIT 5";
	}
	$result = mysql_query($sql, $conn);
	echo mysql_error();	
	$cities = array();
	while($rs = mysql_fetch_assoc($result))
	{
		if(isset($rs['Zip']))
			$cities[] = array('name' => "$rs[City], $rs[State]", 'zip' => $rs['Zip']);
		else
			$cities[] = array('name' => "$rs[City], $rs[State]");
	}
	mysql_close($conn);
	return $cities;
}

$ret = array(
		'fortext' => $entry,
		'results' => SearchCities($entry)
);
 echo json_encode($ret);
// or use json_encode() if it's available on your system
